Online-Academy
Look, Read, Understand, Apply

Threads iii

Threads in Java

  • What is a thread?

    A thread is a lightweight unit of execution within a program. It represents an independent path of execution. A Java program can have multiple threads running concurrently. For example, one thread can handle user input while another performs a calculation. The thread that starts the execution of a Java program is called the main thread.

  • How thread can be created in Java?

    There are two commonly taught ways to create a thread.
    A. By Extending the Thread Class
    Create a class that extends Thread and override its run() method.
    B. By Implementing the Runnable Interface
    Implement Runnable and provide the run() method.
    This approach is generally preferred when the class already needs to extend another class, because Java does not support multiple inheritance of classes.
    C. Using Lambda Expression
    Since Runnable is a functional interface, we can write:

     
    public class Demo {
        public static void main(String[] args) {
            Thread t = new Thread(() -> {
                System.out.println("Thread is running");
            });
            t.start();
        }
    }
    

  • What are the advantages of using Threads?
    • Concurrent Execution: Multiple tasks can make progress concurrently.
    • Better Responsiveness: A program can continue responding to the user while another thread performs a lengthy task
    • Better CPU Utilization: On multi-core processors, multiple threads can execute in parallel, potentially improving performance.
    • Efficient Resource Sharing: Threads within the same process share memory and resources, making communication between them relatively easy.
  • What problem may arise with using multiple threads?

    Although threads are useful, using multiple threads introduces several challenges.

    • Race Condition: A race condition occurs when multiple threads access and modify shared data at the same time, producing unpredictable results.
    • Data Inconsistency: When multiple threads modify shared data without proper synchronization, the data may become inconsistent.
    • Data Inconsistency: When multiple threads modify shared data without proper synchronization, the data may become inconsistent.
    • Thread Overhead: Therefore, creating an unnecessarily large number of threads can actually reduce performance.
    • Difficult Debugging: Multithreaded programs can be difficult to debug because the order in which threads execute can change from one execution to another.
    • Synchronization Problems: When threads share resources, proper synchronization is required. Incorrect synchronization can cause race conditions, deadlocks, or reduced performance.

Threads allow Java programs to perform multiple tasks concurrently, but shared resources must be managed carefully to avoid race conditions, data inconsistency, deadlocks, and excessive resource consumption.

join() makes the current thread wait until the specified thread finishes. join() does not start the thread. Since t has not been started, there is nothing for join() to wait for, so it returns immediately.

t1.start(); Starts the thread

isAlive(): Checks whether thread is alive. A Java thread returns false from isAlive() if it has not been started yet. Returns true only after the thread has been started and before it has terminated.

One important point: isAlive() does not mean the thread is currently executing. A thread that is sleeping or waiting can still return true.